import json

from sqlalchemy import or_

from easyRead.api import bp
from easyRead.extensions import db
from easyRead.api.errors import bad_request, error_response
from flask import request, jsonify, url_for, g, current_app, make_response
from easyRead.models import LibraryBook


@bp.route('/libraryBooks/', methods=['GET'])  # 搜索查询，若没有则显示全部
def get_library_books():
    search = request.args.get('search')
    library_books_output = []
    if search is None:
        library_books = LibraryBook.query.all()
    else:
        library_books = LibraryBook.query.filter(
            or_(LibraryBook.name.like(f"%{search}%"), LibraryBook.author == search)).all()
    for libraryBook in library_books:
        library_books_output.append(libraryBook.to_json())
    resp = make_response(jsonify(library_books_output))
    return resp


@bp.route('/libraryBooks/<keywords>', methods=['GET'])  # 按标签查询所有的书
def get_library_books_by_keywords(keywords):
    library_books = LibraryBook.query.filter(LibraryBook.keywords == keywords).all()
    library_books_output = []
    for libraryBook in library_books:
        library_books_output.append(libraryBook.to_json())
    resp = jsonify(library_books_output)
    return resp


@bp.route('/libraryBooks/<id>', methods=['DELETE'])  # 删除某个图书馆藏书
def delete_library_book(id):
    library_book = LibraryBook.query.get_or_404(id)
    db.session.delete(library_book)
    try:
        db.session.commit()
    except Exception as e:
        # 回滚会话，取消之前的修改
        db.session.rollback()
    return jsonify()


@bp.route('/libraryBooks/<id>', methods=['PUT'])  # 修改某个藏书
def update_library_books(id):
    library_book = LibraryBook.query.get_or_404(id)
    data = request.get_json()
    if not data:
        return bad_request('You must post JSON data.')

    if 'image' in data:
        library_book.image = data['image']
    if 'name' in data:
        library_book.name = data['name']
    if 'author' in data:
        library_book.author = data['author']
    if 'publisher' in data:
        library_book.publisher = data['publisher']
    if 'publication_date' in data:
        library_book.publication_date = data['publication_date']
    if 'introduction' in data:
        library_book.introduction = data['introduction']
    if 'pages' in data:
        library_book.pages = data['pages']
    if 'keywords' in data:
        library_book.keywords = data['keywords']
    if 'iSBN' in data:
        library_book.iSBN = data['iSBN']
    if 'price' in data:
        library_book.price = data['price']
    if 'borrow_times' in data:
        library_book.borrow_times = data['borrow_times']
    if 'number' in data:
        library_book.number = data['number']
    if 'borrow_num' in data:
        library_book.borrow_num = data['borrow_num']

    try:
        db.session.commit()
    except Exception as e:
        # 回滚会话，取消之前的修改
        db.session.rollback()

    return jsonify()


@bp.route('/libraryBooks/', methods=['POST'])  # 新增藏书
def add_library_book():
    library_book_dict = request.get_json()
    id = library_book_dict.get('id')
    image = library_book_dict.get('image')
    name = library_book_dict.get('name')
    author = library_book_dict.get('author')
    publisher = library_book_dict.get('publisher')
    publication_date = library_book_dict.get('publication_date')
    introduction = library_book_dict.get('introduction')
    pages = library_book_dict.get('pages')
    keywords = library_book_dict.get('keywords')
    iSBN = library_book_dict.get('iSBN')
    price = library_book_dict.get('price')
    borrow_times = library_book_dict.get('borrow_times')
    number = library_book_dict.get('number')
    borrow_num = library_book_dict.get('borrow_num')
    library_book = LibraryBook(id, image, name, author, publisher, publication_date, introduction, pages, keywords,
                               iSBN, price, borrow_times, number, borrow_num)
    db.session.add(library_book)
    try:
        db.session.commit()
    except Exception as e:
        # 回滚会话，取消之前的修改
        db.session.rollback()

    return jsonify()